package com.minelx.woods.server.entity;

import com.minelx.woods.server.entity.values.TaskValues;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.types.ObjectId;

public class Task {

	private final MongoCollection<Document> tasksCollection;

	private final String id;

	public Task(MongoCollection<Document> tasksCollection, String id) {
		this.tasksCollection = tasksCollection;
		this.id = id;
	}

	public TaskValues values() {
		Document found = tasksCollection.find(self()).first();
		if (found == null) {
			throw new IllegalArgumentException("finding a non-exists task.");
		}
		return TaskValues.from(found);
	}

	public void markAs(int condition) {
		UpdateResult result = tasksCollection.updateOne(self(), new Document("$set", new Document("condition", condition)));
		if (result.getModifiedCount() != 1) {
			throw new IllegalStateException("condition already modified as: " + condition);
		}
	}

	private Document self() {
		return new Document("_id", new ObjectId(id));
	}
}
